import React, { useState, useEffect } from "react";
import './navbar.scss'
import BottomNavigation from '@material-ui/core/BottomNavigation';
import BottomNavigationAction from '@material-ui/core/BottomNavigationAction';
import ListIcon from '@material-ui/icons/List';
import FavoriteIcon from '@material-ui/icons/Favorite'
import { useHistory } from "react-router-dom";
import { debug } from "console";

const whiteUrl = ['#/', '#/modules'];

export default function Navbar(props: any) {
    interface Nav {
        name: string;
        to: string;
        go: string;
        icon: any
    }

    const history = useHistory();

    const navs: Nav[] = [{
        name: '首页',
        to: '#/',
        go: '/',
        icon: <ListIcon />
    }, {
        name: '食谱',
        to: '#/modules',
        go: 'modules',
        icon: <FavoriteIcon />
    }]

    const [value, setValue] = useState('#/');

    const handleNavTo = async (to: string) => {
        setValue(to);
        const nav = navs.find(nav => nav.to === to);
        history.push(nav!.go);
    };

    // 通过路由白名单
    const setLocationVal = () => {
        const url = location.hash;
        setValue(url);
    }
    history.listen(setLocationVal)
    useEffect(setLocationVal);

    return whiteUrl.includes(value) ? (
        <BottomNavigation
            value={value}
            onChange={(event, newValue) => {
                handleNavTo(newValue)
            }}
            showLabels
            className='navbar'

        >
            {
                navs.map(navItem =>
                    <BottomNavigationAction
                        key={navItem.name}
                        value={navItem.to}
                        label={navItem.name}
                        icon={navItem.icon}
                    />)
            }
        </BottomNavigation>
    ) : null;
};